package com.junqi.msg.event.listener;


import cn.hutool.core.util.StrUtil;
import com.junqi.common.entity.Message;
import com.junqi.common.entity.RedisKeyManager;
import com.junqi.msg.entity.SysUser;
import com.junqi.msg.event.UserOnlineEvent;
import com.junqi.msg.event.UserPushMsgEvent;
import com.junqi.msg.utils.JsonUtils;
import com.junqi.msg.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 用户上线监听器
 *
 */
@Slf4j
@Component
public class UserOnlineListener {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void pushMsg(UserOnlineEvent event) {
        String userId = event.getUserId();
        String roomId = event.getRoomId();

        //用户加入房间缓存
        RedisUtil.sSet(RedisKeyManager.generateKey(RedisKeyManager.ROOM_USERS,roomId),userId);

        SysUser sysUser = RedisUtil.get(RedisKeyManager.generateKey(RedisKeyManager.USER_INFO, userId),SysUser.class);
        if(sysUser!=null){
            //组装用户上线消息，加入队列
            Message message=new Message();
            message.setId(RedisUtil.generateId(RedisKeyManager.generateKey(RedisKeyManager.ROOM_MSG_ID,roomId)));
            message.setSendTime(System.currentTimeMillis());
            message.setUserName(sysUser.getUserName());
            message.setUserId(sysUser.getId());
            message.setRoomId(roomId);
            message.setType(3);
            message.setBody("用户上线");
            //消息
            RedisUtil.zAdd(RedisKeyManager.generateKey(RedisKeyManager.ROOM_MSG,roomId),message,Double.valueOf(message.getSendTime()));
            //有新消息入队，启动监听触发消息通知
            applicationEventPublisher.publishEvent(new UserPushMsgEvent(this, roomId));
        }
    }

}
